package com.jeesite.modules.ueditor;

import com.jeesite.common.ueditor.PathFormat;
import com.jeesite.common.ueditor.define.AppInfo;
import com.jeesite.common.ueditor.define.BaseState;
import com.jeesite.common.ueditor.define.FileType;
import com.jeesite.common.ueditor.define.State;
import com.jeesite.common.ueditor.upload.Base64Uploader;
import com.jeesite.common.ueditor.upload.StorageManager;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.aliyun.oss.service.impl.OssFileUploadServiceExtendImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class OssBase64Uploader extends Base64Uploader {
    public static final State ossSave(HttpServletRequest request, String content, Map<String, Object> conf) {

        byte[] data = decode(content);

        long maxSize = ((Long) conf.get("maxSize")).longValue();

        if (!validSize(data, maxSize)) {
            return new BaseState(false, AppInfo.MAX_SIZE);
        }
        String suffix = FileType.getSuffix("JPG");
        String savePath = PathFormat.parse((String) conf.get("savePath"),
                (String) conf.get("filename"));
        savePath = savePath + suffix;
        State storageState = new BaseState();
        ((BaseState) storageState).setState(true);
        OssFileUploadServiceExtendImpl ossFileUploadServiceExtend = SpringUtils.getBean(OssFileUploadServiceExtendImpl.class);
        ossFileUploadServiceExtend.uploadFile(null, data, savePath);
        if (storageState.isSuccess()) {
            String ctx = request.getContextPath(); // ThinkGem 修正上传图片后返回无contextpath问题
            storageState.putInfo("url", PathFormat.format(savePath));
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", "");

            // UEditor上传文件成功后调用事件
            StorageManager.uploadFileSuccess(savePath, storageState);
        }

        return storageState;
    }


}
